<template>
  <el-card class="login-card">
    <h2 class="title">管理员登录</h2>
    <el-form :model="form" :rules="rules" ref="formRef" label-position="top" :hide-required-asterisk="true">
      <el-form-item label="账号" prop="username">
        <el-input v-model="form.username" placeholder="请输入账号" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" placeholder="请输入密码" show-password />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="submitForm">登录</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import axios from 'axios'
import request from "@/apps/admin/utils/request";
import {useRouter} from "vue-router";


// 表单数据
const form = reactive({
  username: '',
  password: ''
})

// 表单引用
const formRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 表单校验规则
const rules: FormRules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 6, max: 16, message: '账号不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码不正确', trigger: 'blur' }
  ]
}
const router = useRouter()
// 登录请求
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {

        const response = await request.post('/v1/admin/login', {
          username: form.username,
          password: form.password
        }).then(body => {
          console.log(body)
          if (body["code"] !== 200){
            ElMessage.error(body["msg"])
            return;
          }

          let token = body.data["token"]

          localStorage.setItem("adminUsername", form.username);
          localStorage.setItem("adminToken", token);
          localStorage.setItem("adminPermissions", body.data.permissions);
          router.push({name: "dashboard"})
          ElMessage.success("登录成功")
          return;
        })

      } catch (err: any) {
        ElMessage.error(err.response?.data?.message || '登录失败')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-card {
  max-width: 400px;
  margin: 100px auto;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  border-radius: 12px;
}
.title {
  text-align: center;
  margin-bottom: 24px;
}
</style>
